<?php

class RightMenuHelper{

	public function hidden(){
		return false;
	}

	public function active(Structure $node){

		if($node->isChildrenOf($this->getAction()->getRoute()->getObject()) ||
				$node['id'] == $this->getAction()->getRoute()->getObject()->getId()){
			return true;
		}

		return false;
	}

	public function getItemChildren($node, $params){
		$result = array();

		$q = StructureTable::getNodeChildrenQuery($node);
		StructureTable::commonActivityConstraints($q);

		foreach($q->execute() as $child){

			if($params){
				$linkParams = array(
					'node' => $child,
					'params' => array_merge(
						$params,
						array('p'.($child['level']-1) => $child['slug'])
					));
			}else{
				$linkParams = array('node' => $child);
			}

			$result[] = array(
				'title' => $child['title'],
				'link' => $this->getAction()->getComponent('linker', 'articleLinkBuilder', $linkParams),
				'active' => $this->active($child),
				'hidden' => $this->hidden($child),
				'node' => $child,
				'level' => $child['level'],
				'slug' => $child['slug'],
				'id' => $child['id']
			);
		}


		/* starting from 3rd level there is a possibility to put Products in menu
		 * if they r associated with parent menu item (Structure)
		 *  */
		if($node['level'] > 2){
			$this->getProductsItems($result,$node);
		}

		return $result;
	}


	// constraints for future events
	public function setConstraintsOnEvents($q,$node){
		$q->andWhere($q->getRootAlias().'.id = ?', $node['id']);
			if($q->hasAliasDeclaration('p')){
				$q->orderBy('p.scheduled asc')
					->innerJoin('p.ProductPictures pp WITH pp.parameter = ?', 'cover')
					->innerJoin('p.Translation t WITH t.lang = ? and t.name != ""', $this->getAction()->getUser()->getCulture())
					->addSelect('t.*')
					->addSelect('pp.*')
					->andWhere('p.scheduled > NOW()');
			}

		return $q;
	}

	public function getAction(){
		return sfContext::getInstance()->getActionStack()->getFirstEntry()
					->getActionInstance();
	}


	public function getProductsItems(&$result, $node){
			$q =  ProductTable::getStructureProductsQuery();
			ProductTable::commonActivityConstraints($q, $this->getAction()->getUser()->getCulture());
			$this->setConstraintsOnEvents($q,$node);

			foreach(ProductTable::normalizeAssociatedProducts($q) as $item){
				foreach($item['products'] as $new){

					$active =
						$this->getAction()->getRoute()->getProductObject() ?
							$this->getAction()->getRoute()->getProductObject()->getId() == $new['id'] :
							false;



					$result[] = array(
						'title' => $new['name'],
						'link' => $this->getAction()->getComponent('linker','product',array('product'=>$new, 'linkStruct' => $item['node'])),
						'active' => $active,
						'hidden' => false,
						'level' => false,
						'slug' => false,
						'product' => $new,//->toArray(),
						'id' => $new['id']
					);
				}
			}
	}
	

}